﻿/*
This file is part of buco.  
Copyright (c) 2012 Christopher Pawelzik <christopher@cpawelzik.com>

Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 
*/ 

// This is used to simplify JSON-RPC calls within the buco Web Client 

// Create a new proxy object with the supported methods
buco.rpc = new JSONRPCProxy("/json-rpc", 
	[
	"getComposition",
	"addBundle", 
	"setBundlePosition", 
	"checkIntegrity", 	
	"newComposition", 
	"toggleWire",
	"removeBundle", 
	"undo",
	"redo",
	"importComposition"
	]
); 
	
function JSONRPCProxy(url, methodNames) { 	
	this.url = url; 			
	this.counter = 0; 
	// Dynamically implement the given methods on the object
	for(var i = 0; i < methodNames.length; i++) {					
		var name = methodNames[i];		
		var implement = function(name) {			
			JSONRPCProxy.prototype[name] = function(obj) { this.call(name, obj); }		
		}(name); 		
	}
}

JSONRPCProxy.prototype.call = function(methodName, obj) { 			
	var req = {jsonrpc:'2.0', method: methodName, id:this.newID()}; 
	if(obj.params != null) { 
		req.params = obj.params; 
	}	
	$.ajax({
		url: this.url, 
		data: JSON.stringify(req), 
		type: "POST",
		contentType: "application/json", 
		success: function(rpcRes) { 
			if(rpcRes.error == null) {
				if(obj.onSuccess != null) {
					obj.onSuccess(rpcRes.result);
				}
			} else { 				
				if(obj.onError != null) { 					
					obj.onError(rpcRes.error); 
				}
			}
		}, 
		error: function(err, status, thrown) { 
			buco.log(err);
		}		
	});	
};

JSONRPCProxy.prototype.newID = function() { 	
	this.counter++; 
	return this.counter;
}